

import { View, Text, Button, Image } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import React, { useState, useEffect, Suspense } from 'react'
import { Switch, ConfigProvider, Overlay } from '@antmjs/vantui'
import arrowIcon from '@/assets/images/arrow.png'
import arrowRightIcon from '@/assets/images/arrow-right.png'
import { IResponseSuccess, IShopUserLoginUserInfo, IShopUserProfileSwitchOrder, USER_PROFILE_STATUS } from '@/typing'
import { API_URL } from '@/common/serviveApi'
import useProfileStatusAction from '@/hooks/useProfileStatusAction'
import useProfileInfoAction from '@/hooks/useProfileInfoAction'
import { handleCleanStore, handleInitLogin, handleInitStoreBaseInfo, handleLoginCallback, showToast, toPage } from '@/common/util'
import { APP_ID, DEFAULT_AVATAR, PAGE_PATH, PAGE_TYPE, RESPONSE_CODE, STORE_KEY } from '@/common/config'
import { handleUserprofileSwitchOrder } from '@/common/service'
import { useStore } from '@/store';
import { observer } from 'mobx-react-lite';
const JoinNoticeDialog = React.lazy(() => import('@/components/joinNoticeDialog/joinNoticeDialog'));
import './my.scss'


export enum USER_PROFILE_TEXT {
  unknown = '入驻后可接单',
  pending = '信息审核中',
  disable = '入驻审核不通过'
}

const My: React.FC = () => {
  // const { jobStore ,serviceStore} = useStore()
  const { agreementsStore } = useStore()

  const [loading, setLoading] = useState(false);
  const [showNoticeDialog, setShowNoticeDialog] = useState(false)
  const { handleInitStoreProfileInfo } = useProfileInfoAction();
  const { userProfileStatus, profileRemark, handleInitProfileStatus, switchStatus, setSwitchStatus, subscribeQrCodeUrl, handleInitProfileStatusPromise } = useProfileStatusAction();
  const [noticeShow, setNoticeShow] = useState(false)
  const [userInfo, setUserInfo] = useState<IShopUserLoginUserInfo>({
    username: '',
    avatar: '',
    id: 0,
    mobile: '',
    token: '',
    status: '',
    nickname: ''
  });
let pageTimeOut;
  //初始化个人信息 
  const handleInitUserInfo = async () => {
    const userId = Taro.getStorageSync(STORE_KEY.USER_ID);
    // await handleInitProfileStatus()
    console.log(`userid----${userId}`)
    if (userId) {
      handleInitStoreProfileInfo();
      setTimeout(() => {
        const baseUserInfo = handleInitStoreBaseInfo();
        console.log(baseUserInfo)
        const storeUserInfo = JSON.parse(Taro.getStorageSync(STORE_KEY.USER_INFO) || '{}');
        if (baseUserInfo && baseUserInfo['avatar']) {
          

          const avatarModify = baseUserInfo['modify_field']['avatar']
          const nicknameModify = baseUserInfo['modify_field']['nickname']

          if (avatarModify === USER_PROFILE_STATUS.enable) {
            storeUserInfo['avatar'] = baseUserInfo['avatar']
          } else {
            const storeAvatar = Taro.getStorageSync(STORE_KEY.EDIT_AVATAR)
            if (storeAvatar) {
              storeUserInfo['avatar'] = storeAvatar
            }
          }
          if (nicknameModify === USER_PROFILE_STATUS.enable) {
            storeUserInfo['nickname'] = baseUserInfo['nickname']

          } else {
            const storeNickName = Taro.getStorageSync(STORE_KEY.EDIT_NICKNAME)
            if (storeNickName) {
              storeUserInfo['nickname'] = storeNickName
            }
          }
          setUserInfo(storeUserInfo);
        }else{
          setUserInfo(storeUserInfo);
        }
      }, 500)

      // handleInitUserInfoT()

    } else {


      handleInitUserInfo();

    }

    // TODO: 获取用户信息

  }
  //点击申请入驻
  const handleOtherStatusAction = () => {
    // handleCleanStore();
    if (userProfileStatus === USER_PROFILE_STATUS.disable) {
      handleCleanStore();
      
      toPage(PAGE_TYPE.USER_JOIN_INFO)

    } else if (userProfileStatus === USER_PROFILE_STATUS.unknown) {
      // Taro.hideTabBar();
      setNoticeShow(true)

    } else if (userProfileStatus === USER_PROFILE_STATUS.pending) {

      Taro.navigateTo({
        url: `${PAGE_PATH.EXAMINE_PROCESS}?pageEntry=1`
      })
    }
  }

  //接单开关
  const handleSetSwitchStatus =  (statusT) => {

    handleInitProfileStatusPromise().then(async(res) => {
      if (res.code === RESPONSE_CODE.SUCCESS) {
        const status = res.data.status;
        if (status === USER_PROFILE_STATUS.enable) {
          Taro.removeStorageSync(STORE_KEY.PHONE)

          const loginR = await handleInitLogin() as IShopUserLoginUserInfo

          const { status } = loginR

          if (status === USER_PROFILE_STATUS.enable) {
            Taro.showLoading({
              title: '切换中...',
              mask: true,

            })
            // setSwitchStatus(statusT)
            const switchRes = await handleUserprofileSwitchOrder() as IResponseSuccess<IShopUserProfileSwitchOrder>
            Taro.hideLoading()
            if (switchRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS) {
              const switchData = switchRes.data
              if (switchData.code === RESPONSE_CODE.SUCCESS) {
                setSwitchStatus(statusT)
                showToast(switchData.msg)

              } else if (switchData.code === RESPONSE_CODE.LOGIN_EXPIRE || switchData.code === RESPONSE_CODE.LOGIN_NEED) {
                showToast(switchData.msg)
                handleSetSwitchStatus(statusT)
              } else {
                showToast(switchData.msg)
              }
            } else {
              showToast('服务器异常')
            }
          } else {
            showToast('账号异常')
          }
        } else {
          showToast(USER_PROFILE_TEXT[userProfileStatus])


        }

      } else if (res.code === RESPONSE_CODE.LOGIN_EXPIRE || res.code === RESPONSE_CODE.LOGIN_NEED) {
        handleLoginCallback(() => handleSetSwitchStatus(statusT))
      }
    })

  }
  const handleGoPersonPage = async () => {
    //  await handleInitStoreProfileInfo()
    toPage(PAGE_TYPE.PERSIONINFO)
    
  }
  const handleGoAction = () => {
    handleCleanStore();
    handleInitStoreProfileInfo();
    pageTimeOut= setTimeout(() => {
      toPage(PAGE_TYPE.USER_JOIN_INFO)
    }, 300);
    
  }


  const handleGoWxMiniProgram = () => {
    const accountInfo = Taro.getAccountInfoSync();
    const envVersion = accountInfo.miniProgram.envVersion

    Taro.navigateToMiniProgram({
      appId: APP_ID,
      envVersion: envVersion,
      path: `packageMake/pages/tochatDetail/tochatDetail?id=${userInfo.id}&pageEntrance=blog`,
      success: function (res) {
        // 打开成功
      }
    })
  }


  useDidShow(() => {


    const initData = async () => {
      const phone = Taro.getStorageSync(STORE_KEY.PHONE) || ''
      if (phone) {
        handleInitProfileStatus();
        await handleInitUserInfo();
        setLoading(true);

      }


    };
    initData();


  })
  useEffect(() => {



    agreementsStore.handleInitPrivacy()

    return () => {
      if (pageTimeOut) {
        clearTimeout(pageTimeOut);
    }
    

    }
  }, [])
  useEffect(() => {
    if (noticeShow || showNoticeDialog) {
      Taro.hideTabBar()
    } else {
      Taro.showTabBar()
    }


  }, [noticeShow, showNoticeDialog]);

  return (
    <>

      {loading && <View className='min-h-100vh bg-#F6F6F6 my-page box-border'>
        <View className='w-full bg-#fff box-border pl-42px pr-56px pt-32px pb-36px flex items-center '>
          <View className='w-108px h-108px rounded-108px overflow-hidden'>
            {userProfileStatus === USER_PROFILE_STATUS.enable ? <Image src={`${API_URL}${userInfo.avatar}`} className='w-108px h-108px'></Image> : <Image src={DEFAULT_AVATAR} className='w-108px h-108px'></Image>}

          </View>

          <View className='ml-26px flex-1 box-border'>
            <View className='text-#161618 text-36px font-bold'>{userInfo.nickname}</View>
            {userProfileStatus === USER_PROFILE_STATUS.enable ? <View className='mt-14px flex items-center justify-between'>
              <View className='text-28px'>
                <Text className='text-#555'>ID: {userInfo.id}</Text>
                {/* <Text className='text-#8232E8 ml-10px' onClick={handleCopyId}>复制</Text> */}
              </View>
              <View className='flex items-center' onClick={handleGoWxMiniProgram}>
                <Text className='text-#555 text-28px'>个人主页</Text>
                <Image src={arrowIcon} className='w-13px h-23px ml-12px'></Image>
              </View>
            </View> : <View className='mt-14px flex items-center' onClick={handleOtherStatusAction}>
              <Text className='text-#161618 text-28px font-medium'>{USER_PROFILE_TEXT[userProfileStatus]}</Text>
              {profileRemark && <Text className='text-#161618 text-28px font-medium'>（{profileRemark}）</Text>}

              <Image src={arrowIcon} className='w-13px h-23px ml-14px'></Image>
            </View>}



          </View>
        </View>
        <View className='px-21px mt-20px'>
          <View className='bg-#fff'>
            <View className='pt-44px pl-36px pb-32px pr-46px box-border flex items-center justify-between'>
              <View>
                <View className='text-#161618'>接单</View>
                <View className='mt-12px text-#666 text-24px'>开启后可接收新订单</View>
              </View>
              <ConfigProvider themeVars={{ switchHeight: '58rpx', switchWidth: '104rpx', switchBorder: '0' }}>
                <Switch checked={switchStatus} onChange={(e) => handleSetSwitchStatus(e.detail)} activeColor='#8232E8' inactiveColor='#F6F6F6' />
              </ConfigProvider>

            </View>
            {/* {wxApppsubscribe === 0 && <>
              <View className='pl-38px pr-44px box-border'>
                <View className='w-full h-2px bg-#E9E9E9'></View>
              </View>
              <View className='px-36px pt-38px pb-40px box-border flex items-center' onClick={() => setShowNoticeDialog(true)}>
                <Text className='text-#161618 text-28px'>关注公众号接收新订单等消息通知</Text>
                <Image className='ml-12px w-17px h-30px mt-4px' src={arrowRightIcon}></Image>
              </View>
            </>} */}


          </View>
          <View className='mt-20px bg-#fff'>



            <View className='w-708px h-124px flex items-center justify-between box-border pl-36px pr-46px' onClick={() => toPage(PAGE_TYPE.SETTING)}>
              <Text className='text-#161618 text-32px'>设置</Text>
              <Image className=' w-17px h-30px' src={arrowRightIcon}></Image>
            </View>
          </View>
          {userProfileStatus === USER_PROFILE_STATUS.enable && <View className='mt-20px bg-#fff' onClick={handleGoPersonPage}>
            <View className='w-708px h-124px flex items-center justify-between box-border pl-36px pr-46px'>
              <Text className='text-#161618 text-32px'>个人信息</Text>
              <Image className=' w-17px h-30px' src={arrowRightIcon}></Image>
            </View>
          </View>}
          <View className='mt-20px bg-#fff relative'>
            <View className='w-708px h-124px flex items-center justify-between box-border pl-36px pr-46px'>
              <Text className='text-#161618 text-32px'>联系客服</Text>
              <Image className=' w-17px h-30px' src={arrowRightIcon}></Image>
            </View>
            <Button className="service-button bg-transparent  mx-0 px-0 border-transparent w-708px h-124px absolute left-0 top-0" openType="contact" sessionFrom='sessionFrom'></Button>

          </View>
        </View>
      </View>}
      <Suspense>
        <JoinNoticeDialog noticeShow={noticeShow} handlePopStatus={(popStatus) => setNoticeShow(popStatus)} handleGoAction={handleGoAction}></JoinNoticeDialog>
      </Suspense>

      <Overlay show={showNoticeDialog} lockScroll={true}>
        <View className="flex items-center justify-center w-full h-full">
          <View className="w-600px bg-#fff rounded-40px pt-50px box-border flex flex-col items-center" >
            <View className='text-#333333 font-bold text-34px'>关注公众号</View>
            <View className='text-#666666  text-30px mt-32px'>接收新预约单等消息通知</View>
            <Image className='w-214px h-214px mt-40px' src={subscribeQrCodeUrl} showMenuByLongpress={true}></Image>
            <View className='text-#333333 text-30px mt-10px'>长按二维码识别</View>
            <View className='border-#E8E8E8 border-1px border-solid border-l-0 border-r-0 border-b-0 mt-60px w-600px h-94px box-border flex items-center justify-center text-#333333 text-30px font-medium' onClick={() => setShowNoticeDialog(false)}>关闭</View>
          </View>
        </View>
      </Overlay>

    </>
  )
}
export default observer(My);
